package com.yswl;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by MyPC on 2018/2/23.
 */

public class MyIntentModule extends ReactContextBaseJavaModule implements ActivityEventListener {

    private static final String HEAD_IMAGE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/HeadImage/";
    private static final String HEAD_IMAGE_NAME = "head_image.png";
    private static final String FILE_PATH = "/sdcard/syscamera.jpg";
    // startActivityForResult 的 requestCode
    private static final int REQUEST_CODE_CAMERA = 0;
    private static final int REQUEST_CODE_GALLERY = 1;
    private static final int REQUEST_CODE_CROP = 2;

    private Promise mPromise = null;
    private Uri mUri = null;
    private String mFullPath = null;
    private Callback mcall;

    public MyIntentModule(ReactApplicationContext reactContext) {
        super(reactContext);
        reactContext.addActivityEventListener(this);
    }

    @Override
    public String getName() {
        return "IntentModule";
    }
    @ReactMethod
    public void startActivityFromJS(String name, String params){
        try{
            Activity currentActivity = getCurrentActivity();
            if(null!=currentActivity){
                Class toActivity = Class.forName(name);
                Intent intent = new Intent(currentActivity,toActivity);
                intent.putExtra("params", params);
                currentActivity.startActivity(intent);
            }
        }catch(Exception e){
            throw new JSApplicationIllegalArgumentException(
                    "不能打开Activity : "+e.getMessage());
        }
    }

    @ReactMethod
    public void callCamera(Callback sCall) { // 调用相机的方法
        Log.e("RZC","call camera...");
        recursionDeleteFile();
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        mcall = sCall;
        if (isPathExists()) {
            mFullPath = HEAD_IMAGE_PATH + System.currentTimeMillis() + ".png";
            mUri = Uri.fromFile(new File(mFullPath));
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
            Activity activity = getCurrentActivity();
            Log.e("RZC","activity :"+activity);
            if (activity != null) {
                //mPromise = promise;
                activity.startActivityForResult(intent, REQUEST_CODE_CAMERA);
            }
        }

    }

    @ReactMethod
    public void getImageUri(Promise promise) {
        Uri uri = Uri.fromFile(new File(HEAD_IMAGE_PATH + HEAD_IMAGE_NAME));
        promise.resolve(uri.toString());
    }

    @ReactMethod
    public void isImageExists(Promise promise) {
        boolean isExists = isHeadImageExits();
        promise.resolve(isExists);
    }

    private Intent cropImage(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 800);
        intent.putExtra("outputY", 800);
        intent.putExtra("return-data", false);
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(new File(mFullPath)));
        intent.putExtra("outputFormat", "png");
        return intent;
    }


    @Override
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
        Log.e("RZC","onActivityResult");
        if (requestCode == REQUEST_CODE_CAMERA) { // 调用相机回调
            Log.e("RZC","REQUEST_CODE_CAMERA");
            if (resultCode == Activity.RESULT_OK) { // *************1.拍照完成，将进入裁剪界面
                activity.startActivityForResult(cropImage(mUri), REQUEST_CODE_CROP);// 启动裁剪界面
            } else if (resultCode == Activity.RESULT_CANCELED) { // 拍照界面点击取消

            }
        } else if (requestCode == REQUEST_CODE_CROP) { // ************2.裁剪完成
            Log.e("RZC","REQUEST_CODE_CROP");
            if (resultCode == Activity.RESULT_OK) {
                //mPromise.resolve(mUri.toString());
                // 将临时图片复制一份，保存为最终的头像图片
                mcall.invoke(mUri.toString());
                saveHeadImage();
            } else if (resultCode == Activity.RESULT_CANCELED) {
                //mPromise.resolve(null);
                new File(mFullPath).delete();
            }
        }
    }

    private boolean isPathExists() {
        File file = new File(HEAD_IMAGE_PATH);
        if (!file.exists()) {
            file.mkdirs();
        }
        return file.exists();
    }

    private boolean isHeadImageExits() {
        File file = new File(HEAD_IMAGE_PATH + HEAD_IMAGE_NAME);
        return file.exists();
    }

    private void saveHeadImage() {
        try {
            File file = new File(HEAD_IMAGE_PATH + HEAD_IMAGE_NAME);
            if (file.exists()) {
                file.delete();
            }
            InputStream from = new FileInputStream(mFullPath);
            OutputStream to = new FileOutputStream(HEAD_IMAGE_PATH + HEAD_IMAGE_NAME);
            byte bt[] = new byte[1024];
            int c;
            while ((c = from.read(bt)) > 0) {
                to.write(bt, 0, c);
            }
            from.close();
            to.close();
        } catch (Exception e) {
        }
    }

    public void recursionDeleteFile() {
        File file = new File(HEAD_IMAGE_PATH);
        File[] childFile = file.listFiles();
        if (childFile == null || childFile.length == 0) {
            return;
        }
        for (File f : childFile) {
            if (f.getName().contains(HEAD_IMAGE_NAME))
                continue;
            f.delete();
        }
    }


    @Override
    public void onNewIntent(Intent intent) {

    }
}